import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      // 用户名前后去掉空格
      login({ username: username.trim(), password: password })
        .then((response) => {
          // 获取返回值中的 data
          const { data } = response;
          // 调用 mutations 中 SET_TOKEN 方法，将 token 存到 vuex 中
          commit("SET_TOKEN", data.token);
          // 使用 js-cookie 插件，将 token 存入本地cookie中
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response;

          if (!data) {
            return reject("认证失败，请重新登录！");
          }
          // 将 name 修改为 nickname ，因为自定义的接口返回信息为 nickname
          const { nickname, avatar } = data;
          // 登录成功之后把 nickname 和 avatar 存到 vuex 中，这样所有页面都可以访问了
          commit("SET_NAME", nickname);
          commit("SET_AVATAR", avatar);
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first 使用js-cookie插件，删除cookie中的token
          resetRouter(); // 重置路由
          commit("RESET_STATE");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE"); // 将 vuex 中的值恢复到默认值
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
